package thread;

import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-08-29
 * Time: 16:30
 */

/*
编写代码, 实现多线程数组求和.
1.给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
2.实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
3.其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
4.最终再汇总两个和, 进行相加
5.记录程序的执行时间.
 */
public class Demo1 {
    volatile public static int sum = 0;

    public static void main(String[] args) throws InterruptedException {
        int[] q = new int[1000_0000];
        Random random = new Random();
        for(int i = 0; i < 1000_0000; i++){
            q[i] = random.nextInt(100) + 1;  //生成随机数放到数组中
        }
        long start = System.currentTimeMillis();  //记录下开始的时间
        Thread thread1 = new Thread(() -> {
            for(int i = 0; i < 1000_0000; i += 2){
                synchronized (Demo1.class){
                    sum += q[i];
                }
            }
        });
        Thread thread2 = new Thread(() -> {
            for(int i = 1; i < 1000_0000; i += 2){
                synchronized (Demo1.class){
                    sum += q[i];
                }
            }
        });

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        long end = System.currentTimeMillis();  //记录结束时间
        System.out.println("和为:" + sum);
        System.out.println("时间为:" + (end - start) + "ms");
    }
}
